#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
// ./tcp_client ip port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cout << "正确用法:./tcp_client server_ip server_port" << endl;
        exit(-1);
    }
    string server_ip = argv[1];
    int16_t server_port = stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        cerr << "套接字创建失败" << endl;
    }
    cout << "套接字创建成功,sockfd:" << sockfd << endl;

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());
    server.sin_port = htons(server_port);
    int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
    if (n < 0)
    {
        cerr << "获取连接失败" << endl;
    }
    cout << "获取连接成功" << endl;

    while (true)
    {
        string request;
        cout << "请输入信息:";
        getline(cin, request);
        int send_code = write(sockfd, request.c_str(), 1024);
        if (send_code > 0)
        {
            // 发送成功
            char response[1024];
            int n = read(sockfd, response, sizeof(response));
            if (n > 0)
            {
                // 接收成功
                response[n] = '\0';
                cout << "server from a response # " << response << endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            // 发送失败
            cout << request << "---发送失败" << endl;
            break;
        }
    }
    return 0;
}